<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 用户收藏的泰山号文章格式化
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300010_000010_t_cms_article_favorite extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%user_favorite}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from($this->tableName)
        ->where([
            'model' => 'ts_article'
        ]);
        $this->handleProgress($query, [$this, 'evenDule']);
        $this->update($this->tableName, [
            'model' => 'cms_article',
        ], ['model' => 'article']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }
        foreach ($rows as $row) {
            $articleid = (new Query())->from('{{%cms_article}}')
            ->select('id')
            ->where(['id' => $row['model_id']])
            ->scalar();
            if (!$articleid) {
                continue;
            }
            $migration->db->createCommand()->update($migration->tableName, [
                'model' => 'cms_article',
                'model_id' => $articleid,
            ], ['id' => $row['id']])->execute();
        }
    }

}
